﻿/*
 * Divisionsmatch - beregning af resultater
 * Copyright (C) 2013 Anders Klinting
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Printing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using System.Xml.Serialization;
using CommandLineParser.Arguments;
using Microsoft.Win32;
using AutoUpdaterDotNET;

namespace Divisionsmatch
{
    public partial class frmDivi : Form
    {
        #region member variables
        public static string autoUpdateSiteURL = @"http://code.google.com/p/divisionsmatch/downloads/list";
        public static string autoUpdateURL = @"http://www.fif-orientering.dk/divisionsmatch/versioninfo.xml";
        private Hashtable ieOriginalPageSetup = new Hashtable();
        private Hashtable ieNewPageSetup = new Hashtable();
        private Config config = new Config(true);
        private string configFile = "(uden titel)";
        private Staevne mitstaevne = new Staevne();
        private FileSystemWatcher watcher = null;
        private string _txtResultatFil = string.Empty;

        private bool _isModified = false;
        private bool isModified
        {
            get
            {
                return _isModified;
            }

            set
            {
                _isModified = value;
                this.Text = "Divisionsmatch - " + Path.GetFileName(configFile);
                if (value == true)
                {
                    this.Text += " *";
                }
            }
        }
        #endregion

        #region constructor
        public frmDivi(string[] args)
        {
            InitializeComponent();
#if DEBUG
            txtCSVFile.Text = @"C:\temp\divisionsturnering\divi20100530klasse.csv";
#endif

            try
            {
                // get original pageSetup values for IE
                using (RegistryKey key = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Internet Explorer\PageSetup", true))
                {
                    if (key == null)
                        return;

                    ieOriginalPageSetup.Add("margin_left", (string)key.GetValue("margin_left"));
                    ieOriginalPageSetup.Add("margin_right", (string)key.GetValue("margin_right"));
                    ieOriginalPageSetup.Add("margin_top", (string)key.GetValue("margin_top"));
                    ieOriginalPageSetup.Add("margin_bottom", (string)key.GetValue("margin_bottom"));
                    ieOriginalPageSetup.Add("header", (string)key.GetValue("header"));
                    ieOriginalPageSetup.Add("footer", (string)key.GetValue("footer"));

                    // duplicate
                    foreach (var x in ieOriginalPageSetup.Keys)
                    {
                        ieNewPageSetup.Add(x, ieOriginalPageSetup[x]);
                    }
                }
            }
            catch
            {
            }

            if (args.Length > 0)
            {
                if (_doBatch(args))
                {
                    Environment.Exit(0);
                }
            }

            AutoUpdater.LetUserSelectRemindLater = true;
            AutoUpdater.Start(autoUpdateURL);
        }
        #endregion

        #region form, button event handlers

        #region løb menu handlers
        private void nytLøbToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            frmConfig frm = new frmConfig();
            frm.config = new Config(true);
            if (frm.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                Cursor.Current = Cursors.WaitCursor;
                try
                {
                    mitstaevne = new Staevne();
                    config = frm.config;                    
                    configFile = "(uden titel)";
                    isModified = true;

                    panel2.Enabled = true;
                    gemLøbToolStripMenuItem.Enabled = true;
                    redigerToolStripMenuItem.Enabled = true;

                    _resetBeregnOgPrint();
                }
                finally
                {
                    Cursor.Current = Cursors.Default;
                }
            }
        }

        private void åbnLøbToolStripMenuItem_Click(object sender, EventArgs e)
        {
            // åben en gemt konfiguration
            OpenFileDialog openFile = new OpenFileDialog();
            openFile.Filter = "Divisionsmatch filer (*.divi)|*.divi";
            openFile.CheckPathExists = true;
            openFile.AddExtension = true;
            openFile.DefaultExt = ".divi";
            openFile.SupportMultiDottedExtensions = true;
            openFile.Title = "Åbn konfiguration";
            openFile.Multiselect = false;
            if (openFile.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                Cursor.Current = Cursors.WaitCursor;
                try
                {
                    // load file
                    _loadDiviFil(openFile.FileName);

                    mitstaevne = new Staevne();

                    // juster UI
                    _makeNewPageSetup();

                    panel2.Enabled = true;
                    gemLøbToolStripMenuItem.Enabled = true;
                    redigerToolStripMenuItem.Enabled = true;

                    _resetBeregnOgPrint();

                    MessageBox.Show("Løbskonfigurationen er indlæst. Vælg en resultat-fil for at starte beregning");
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Konfigurationen kunnne ikke åbnes \n" + ex.Message + "\n" + ex.StackTrace, "Fejl");
                }
                finally
                {
                    Cursor.Current = Cursors.Default;
                }
            }
        }

        private void redigerToolStripMenuItem_Click(object sender, EventArgs e)
        {
            // Redigerløb  - vis konfiguration
            frmConfig frm = new frmConfig();
            frm.config = config;
            frm.editOnly = true;
            frm.saveFile = configFile;
            if (frm.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                config = frm.config;
                configFile = frm.saveFile;
                isModified = true;

                _resetBeregnOgPrint();

                if (_txtResultatFil != string.Empty)
                {
                    btnBeregn.Enabled = true;
                }
            }
        }

        private void gemLøbToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SaveFileDialog saveFile = new SaveFileDialog();
            saveFile.Filter = "Divisionsmatch filer (*.divi)|*.divi";
            saveFile.OverwritePrompt = true;
            saveFile.CheckPathExists = true;
            saveFile.AddExtension = true;
            saveFile.DefaultExt = ".divi";
            saveFile.SupportMultiDottedExtensions = true;
            saveFile.Title = "Gem konfiguration";
            if (saveFile.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                Cursor.Current = Cursors.WaitCursor;
                try
                {
                    // hack for at sikre printerfilename er sat
                    config.printerSettings.PrintFileName = "dummy.txt";

                    XmlSerializer serializer = new XmlSerializer(typeof(Config));
                    TextWriter writer = new StreamWriter(saveFile.FileName);
                    serializer.Serialize(writer, config);
                    writer.Close();

                    configFile = saveFile.FileName;
                    isModified = false;

                    ///_resetBeregnOgPrint();
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Konfigurationen kunnne ikke gemmes \n" + ex.Message + "\n" + ex.StackTrace, "Fejl");
                }
                finally
                {
                    Cursor.Current = Cursors.Default;
                }
            }
        }

        #endregion

        #region Beregn handlers

        private void btnBeregn_Click(object sender, EventArgs e)
        {
            _beregn();
        }

        private void bntOpenResultFile_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFile = new OpenFileDialog();
            openFile.Filter = "Resultat filer (*.xml, *.csv)|*.xml;*.csv"; //|OE resultat filer (*.csv)|*.csv";
            openFile.CheckPathExists = true;
            openFile.AddExtension = true;
            openFile.DefaultExt = ".csv";
            openFile.SupportMultiDottedExtensions = true;
            openFile.Title = "Åbn resultat";
            openFile.Multiselect = false;
            if (openFile.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                _loadResultatFil(openFile.FileName);

                // juster UI

                txtCSVFile.Text = _txtResultatFil;
                btnBeregn.Enabled = true;

                _watchFile();
                _beregn();
            }
        }

        #endregion

        #region print og font og export

        private void btnPrint_Click(object sender, EventArgs e)
        {
            try
            {
                _doPrint();
            }
            finally
            {
                btnPrint.BackColor = Control.DefaultBackColor;
                btnPrint.UseVisualStyleBackColor = true;
            }
        }

        string HeaderText;
        string TextToPrint;
        List<string> AllTextToPrint = new List<string>();
        int pageNum;
        int grpNum;
        public PrintDocument InitPrint()
        {
            // document skal indeholde en liste af text outputssom hver skal skifte side
            pageNum = 0;
            grpNum = 1;
            this.HeaderText = string.Empty;
            this.AllTextToPrint.Clear();
            this.AllTextToPrint.Add(mitstaevne.printmatcher());
            this.AllTextToPrint.AddRange(mitstaevne.printgrupper());
            if (!config.SideSkift)
            {
                string alltext = string.Empty;
                foreach (string s in AllTextToPrint)
                {
                    if (s!=string.Empty)
                    {
                        alltext += System.Environment.NewLine;
                    }

                    alltext += s;
                }
                
                AllTextToPrint.Clear();
                AllTextToPrint.Add(alltext);
            }

            // fyld tekst i den først side
            this.TextToPrint = this.AllTextToPrint[0];

            PrintDocument PD = new PrintDocument();
            PD.PrinterSettings = config.printerSettings;
            PD.DefaultPageSettings = config.pageSettings;
            PD.OriginAtMargins = true;
            PD.PrintPage += PrintPage;
            return PD;
        }

        public void PrintPage(object sender, PrintPageEventArgs e)
        {
            int Chars = 0;
            int Lines = 0;
            Font Font = config.font;
            Rectangle R = new Rectangle(Point.Empty, e.MarginBounds.Size);
            StringFormat SF = StringFormat.GenericTypographic;

            if (HeaderText.Equals(string.Empty))
            {
                // calcualte the width
                string t = string.Empty;
                while (Lines < 2)
                {
                    t = t + "-";
                    e.Graphics.MeasureString(t, Font, R.Size, SF, out Chars, out Lines);
                }

                HeaderText = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss").PadLeft(t.Length - 1) + "\n" + "".PadLeft(t.Length - 1, '-') + "\n\n";
            }

            pageNum++;
            string sideNum = "side " + pageNum;

            // test if first page is printed
            if (pageNum == 1 || TextToPrint.Length > 0)
            {
                TextToPrint = sideNum + HeaderText.Substring(sideNum.Length) + TextToPrint;

                e.Graphics.MeasureString(TextToPrint, Font, R.Size, SF, out Chars, out Lines);
                e.Graphics.DrawString(TextToPrint, Font, Brushes.Black, R, SF);
                
                TextToPrint = TextToPrint.Substring(Chars);
                e.HasMorePages = TextToPrint.Length > 0 || grpNum < AllTextToPrint.Count();
            }
            else
            {
                if (grpNum < AllTextToPrint.Count())
                {
                    TextToPrint = AllTextToPrint[grpNum++];

                    TextToPrint = sideNum + HeaderText.Substring(sideNum.Length) + TextToPrint;

                    e.Graphics.MeasureString(TextToPrint, Font, R.Size, SF, out Chars, out Lines);
                    e.Graphics.DrawString(TextToPrint, Font, Brushes.Black, R, SF);

                    TextToPrint = TextToPrint.Substring(Chars);
                    e.HasMorePages = TextToPrint.Length > 0 || grpNum < AllTextToPrint.Count();
                }
                else
                {
                    e.HasMorePages = false;
                }
            }

            if (e.HasMorePages == false)
            {
                // gør klar til evt print fra PrintPreview
                pageNum = 0;
                grpNum = 0;
                TextToPrint = AllTextToPrint[0];
            }
        }

        private void _doPrint()
        {
            if (tabControl1.SelectedTab == tabPage1)
            {
                // print text versionen
                _printTxt();
            }
            else
            {
                // print webpage
                _setIEPageSetup(ieNewPageSetup);
                webOutput.ShowPrintDialog();
            }
        }

        private void pageSetupToolStripMenuItem_Click(object sender, EventArgs e)
        {

            //PageSetupDialog settings
            PrintDocument PD = new PrintDocument();
            PD.PrinterSettings = config.printerSettings;
            PD.DefaultPageSettings = config.pageSettings;
            pageSetupDialog1.Document = PD;

            if (pageSetupDialog1.ShowDialog() == DialogResult.OK)
            {
                config.printerSettings = pageSetupDialog1.PrinterSettings;
                config.pageSettings = pageSetupDialog1.PageSettings;
                isModified = true;

                _makeNewPageSetup();
            }
        }

        private void printPreviewToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (tabControl1.SelectedTab == tabPage1)
            {
                PrintPreviewDialog PPDlg = new PrintPreviewDialog();
                PPDlg.Document = InitPrint();
                PPDlg.ShowDialog();
                HeaderText = "";
            }
            else
            {
                _setIEPageSetup(ieNewPageSetup);
                webOutput.ShowPrintPreviewDialog();
            }
        }

        private void printToolStripMenuItem_Click(object sender, EventArgs e)
        {
            btnPrint_Click(sender, e);
        }

        private void vælgFontToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FontDialog fd = new FontDialog();
            fd.FixedPitchOnly = true;
            fd.ShowColor = false;
            fd.ShowApply = false;
            fd.Font = config.font;
            if (fd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                config.font = fd.Font;
                textBox1.Font = fd.Font;

                textBox3.Font = fd.Font;

                _fillOutput();

                isModified = true;
            }
        }

        private void btnEksport_Click(object sender, EventArgs e)
        {
            if (tabControl1.SelectedTab == tabPage2)
            {
                // eksport af HTML
                // webOutput.ShowSaveAsDialog();
                SaveFileDialog saveFile = new SaveFileDialog();
                saveFile.Filter = "HTML filer (*.htm)|*.htm";
                saveFile.OverwritePrompt = true;
                saveFile.CheckPathExists = true;
                saveFile.AddExtension = true;
                saveFile.DefaultExt = ".htm";
                saveFile.SupportMultiDottedExtensions = true;
                saveFile.Title = "Exporter resultat";
                if (saveFile.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    Cursor.Current = Cursors.WaitCursor;
                    try
                    {
                        _exportHtml(saveFile.FileName);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("Resultatet kunnne ikke gemmes \n" + ex.Message + "\n" + ex.StackTrace, "Fejl");
                    }
                    finally
                    {
                        Cursor.Current = Cursors.Default;
                    }
                }
            }
            else
            {
                // eksport af TXT
                SaveFileDialog saveFile = new SaveFileDialog();
                saveFile.Filter = "Text filer (*.txt)|*.txt";
                saveFile.OverwritePrompt = true;
                saveFile.CheckPathExists = true;
                saveFile.AddExtension = true;
                saveFile.DefaultExt = ".txt";
                saveFile.SupportMultiDottedExtensions = true;
                saveFile.Title = "Exporter resultat";
                if (saveFile.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    Cursor.Current = Cursors.WaitCursor;
                    try
                    {
                        _exportTxt(saveFile.FileName);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("Resultatet kunnne ikke gemmes \n" + ex.Message + "\n" + ex.StackTrace, "Fejl");
                    }
                    finally
                    {
                        Cursor.Current = Cursors.Default;
                    }
                }
            }
        }

        #endregion

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (_isModified)
            {
                if (MessageBox.Show("Løbskonfigurationen er ændret men ikke gemt. Vil du stadig lukke?\nTryk på " + DialogResult.OK.ToString() + " for at afslutte uden at gemme. Tryk på " + DialogResult.Cancel.ToString() + " for at returnere så du kan gemme.", "Afslut?", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2) != System.Windows.Forms.DialogResult.OK)
                {
                    e.Cancel = true;
                }

                // reset page setup settings before closing
                _setIEPageSetup(ieOriginalPageSetup);
            }
        }

        private void lukToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void indholdToolStripMenuItem_Click(object sender, EventArgs e)
        {
            _showHelp(false);
        }

        private void omToolStripMenuItem_Click(object sender, EventArgs e)
        {
            frmOm frmOm = new frmOm();
            frmOm.ShowDialog();
        }

        #endregion

        #region internal methods

        internal void _beregn()
        {
            try
            {
                mitstaevne.beregnpoint(config, _txtResultatFil);

                _fillOutput();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Fejl ifm beregning: " + ex.Message, "Fejl", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                // mark print is ready
                btnPrint.BackColor = Color.LightGreen;
            }
        }

        #endregion

        #region private methods

        private void _resetBeregnOgPrint()
        {
            textBox1.Clear();
            textBox3.Clear();
            btnBeregn.Enabled = false;
            btnPrint.Enabled = false;
            btnEksport.Enabled = false;
            printPreviewToolStripMenuItem.Enabled = false;
            printToolStripMenuItem.Enabled = false;
            printMainToolStripMenuItem.Enabled = true;
        }

        private void _setPrintReady()
        {
            textBox1.Enabled = true;
            textBox3.Enabled = true;
            btnPrint.Enabled = true;
            btnEksport.Enabled = true;
            printPreviewToolStripMenuItem.Enabled = true;
            printToolStripMenuItem.Enabled = true;
            printMainToolStripMenuItem.Enabled = true;
            //// vælgFontToolStripMenuItem.Enabled = true;
            //// vælgFontToolStripMenuItem.Enabled = true;
            //// vælgPrinterToolStripMenuItem.Enabled = true;
        }

        private void _fillOutput()
        {
            textBox1.Text = DateTime.Now.ToString("HH:mm:ss") + System.Environment.NewLine + mitstaevne.printmatcher();
            textBox1.Font = config.font.FontValue;

            textBox3.Text = string.Concat(mitstaevne.printgrupper().ToArray());
            textBox3.Font = config.font.FontValue;

            _setPrintReady();

            webOutput.DocumentText = mitstaevne.lavHTML(config);
        }

        private void _watchFile()
        {
            // Create a new FileSystemWatcher and set its properties.
            if (watcher == null)
            {
                watcher = new FileSystemWatcher();
                watcher.Path = Path.GetDirectoryName(txtCSVFile.Text);
                watcher.Filter = Path.GetFileName(txtCSVFile.Text);

                /* Watch for changes in LastWrite times*/
                watcher.NotifyFilter = NotifyFilters.LastWrite;

                // Add event handlers.
                watcher.Changed += new FileSystemEventHandler(_csvFileOnChanged);

                // link to the form
                watcher.SynchronizingObject = this;

                // Begin watching.
                watcher.EnableRaisingEvents = true;
            }
            else
            {
                // update the file to watch for
                watcher.EnableRaisingEvents = false;
                watcher.Path = Path.GetDirectoryName(txtCSVFile.Text);
                watcher.Filter = Path.GetFileName(txtCSVFile.Text);
                watcher.EnableRaisingEvents = true;
            }
        }

        // Define the event handlers. 
        private static DateTime lastRead = DateTime.Now;

        private static void _csvFileOnChanged(object source, FileSystemEventArgs e)
        {
            DateTime lastWriteTime = File.GetLastWriteTime(e.FullPath);
            if (lastWriteTime != lastRead)
            {
                frmBeregnPop pop = new frmBeregnPop();
                try
                {
                    Cursor.Current = Cursors.WaitCursor;

                    (source as FileSystemWatcher).EnableRaisingEvents = false;

                    frmDivi frmDivi = ((source as FileSystemWatcher).SynchronizingObject as frmDivi);

                    pop.StartPosition = FormStartPosition.Manual;
                    pop.Location = new Point(frmDivi.Location.X + (frmDivi.Width - pop.Width) / 2, frmDivi.Location.Y + (frmDivi.Height - pop.Height) / 2);
                    pop.ShowInTaskbar = false;
                    pop.Show();
                    pop.Update();
                    Thread.Sleep(1000);
                    frmDivi._beregn();
                }
                finally
                {
                    pop.Close();
                    (source as FileSystemWatcher).EnableRaisingEvents = true;
                    lastRead = lastWriteTime;
                    Cursor.Current = Cursors.Default;
                }
            }
        }

        private void _setIEPageSetup(Hashtable values)
        {
            using (RegistryKey key = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Internet Explorer\PageSetup", true))
            {
                if (key == null)
                    return;

                foreach (DictionaryEntry item in values)
                {
                    string value = (string)key.GetValue(item.Key.ToString());

                    if (value != item.Value.ToString())
                    {
                        key.SetValue(item.Key.ToString(), item.Value);
                    }
                }
            }
        }

        private void _makeNewPageSetup()
        {
            ieNewPageSetup["margin_left"] = (config.pageSettings.Margins.Left / 100.0).ToString();
            ieNewPageSetup["margin_right"] = (config.pageSettings.Margins.Right / 100.0).ToString();
            ieNewPageSetup["margin_top"] = (config.pageSettings.Margins.Top / 100.0).ToString();
            ieNewPageSetup["margin_bottom"] = (config.pageSettings.Margins.Bottom / 100.0).ToString();
        }


        private void _showHelp(bool batch)
        {
            string helpFilePath = Path.Combine(Application.StartupPath, "Divisionsmatchberegning.chm");
            if (File.Exists(helpFilePath))
            {
                if (batch)
                {
                    System.Diagnostics.Process.Start(helpFilePath);
                }
                else
                {
                    Help.ShowHelp(this, "file://" + helpFilePath);
                }
            }
            else
            {
                MessageBox.Show("Hjælpefilen mangler");
            }
        }

        private void _loadDiviFil(string diviFil)
        {
            config = Config.LoadDivi(diviFil);

            configFile = diviFil;
            isModified = false;
        }

        private void _loadResultatFil(string txtFil)
        {
            _txtResultatFil = txtFil;
        }

        private void _printTxt()
        {
            PrintDialog pDlg = new PrintDialog();
            pDlg.Document = InitPrint();
            pDlg.ShowNetwork = true;
            pDlg.AllowPrintToFile = false;
            pDlg.AllowSelection = false;
            pDlg.AllowSomePages = false;
            pDlg.AllowCurrentPage = false;
            pDlg.PrinterSettings = config.printerSettings;
            if (pDlg.ShowDialog() == DialogResult.OK)
            {
                pDlg.Document.Print();

                HeaderText = "";
            }
        }

        private void _exportHtml(string exportFil)
        {
            File.WriteAllText(exportFil, webOutput.DocumentText, Encoding.Default);
        }

        private void _exportTxt(string exportFil)
        {
            string allText = mitstaevne.printmatcher() + Environment.NewLine + string.Concat(mitstaevne.printgrupper().ToArray());
            File.WriteAllText(exportFil, allText, Encoding.Default);
        }

        private void _printWebPage()
        {
            string batchhtml = @"c:\temp\divi.htm";
            File.WriteAllText(batchhtml, mitstaevne.lavHTML(config), Encoding.Default);

            // Create a WebBrowser instance. 
            WebBrowser webBrowserForPrinting = new WebBrowser();

            // Add an event handler that prints the document after it loads.
            webBrowserForPrinting.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(_printWebDocument);

            // Set the Url property to load the document.
            webBrowserForPrinting.Url = new Uri(batchhtml);

            Thread.Sleep(3000);
            webBrowserForPrinting.Print();
        }

        private void _printWebDocument(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            // Print the document now that it is fully loaded.
            ((WebBrowser)sender).Print();

            // Dispose the WebBrowser now that the task is complete. 
            ((WebBrowser)sender).Dispose();
        }

        private bool _doBatch(string[] args)
        {
            Console.WriteLine("Divisionsmatch -  Copyright (C) 2013 Anders Klinting");
            Console.WriteLine("");
            Console.WriteLine("This program comes with ABSOLUTELY NO WARRANTY; for details see the About page");
            Console.WriteLine("This is free software, and you are welcome to redistribute it");
            Console.WriteLine("under certain conditions");

            CommandLineParser.CommandLineParser parser = new CommandLineParser.CommandLineParser();

            try
            {
                FileArgument diviFil = new FileArgument('d', "Divi", "Divi fil");
                FileArgument resultatFil = new FileArgument('c', "Csv", "resultat csv fil");
                ValueArgument<string> exportFil = new ValueArgument<string>('e', "Export", "Export fil");
                ValueArgument<string> print = new ValueArgument<string>('p', "Print", "print TXT eller WWW");
                SwitchArgument help = new SwitchArgument('h', "Hjælp", false);

                parser.Arguments.Add(diviFil);
                parser.Arguments.Add(resultatFil);
                parser.Arguments.Add(exportFil);
                parser.Arguments.Add(print);
                parser.Arguments.Add(help);

                parser.ParseCommandLine(args);
                
                if (help.Parsed)
                {
                    _showHelp(true);
                }
                else
                {
                    if (diviFil.Parsed)
                    {
                        _loadDiviFil(diviFil.Value.FullName);

                        if (resultatFil.Parsed)
                        {
                            _loadResultatFil(resultatFil.Value.FullName);

                            mitstaevne.beregnpoint(config, _txtResultatFil);

                            if (print.Parsed)
                            {
                                _printTxt();

                                ////if (print.Value.ToUpperInvariant() == "TXT")
                                ////{
                                ////    _printTxt();
                                ////}
                                ////else if (print.Value.ToUpperInvariant() == "WWW")
                                ////{
                                ////    //setIEPageSetup(ieNewPageSetup);
                                ////    _printWebPage();
                                ////    //setIEPageSetup(ieOriginalPageSetup);
                                ////}
                                ////else
                                ////{
                                ////    throw new Exception("hust at skrive '-p TXT' eller '-p WWW' for at printe i batch");
                                ////}
                            }

                            if (exportFil.Parsed)
                            {
                                _exportTxt(exportFil.Value);
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                MessageBox.Show("Noget gik galt: " + Environment.NewLine + e.Message, "Fejl", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            return true;
        }
        #endregion

        private void setupPrinterToolStripMenuItem_Click(object sender, EventArgs e)
        {
            frmSetup sp = new frmSetup();
            sp.config = config;

            if (sp.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {

                config = sp.config;

                isModified = true;

                textBox1.Font = config.font;
                textBox3.Font = config.font;

                _fillOutput();

                _makeNewPageSetup();
            }
        }

        private void checkForOpdateringerToolStripMenuItem_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start(autoUpdateSiteURL);
        }
    }
}
